package com.jin.webvideo.externalInterfaces.spi.videosearch;

import com.jin.webvideo.base.util.CollectionsUtil;
import com.jin.webvideo.entity.VideoInfo;
import com.jin.webvideo.entity.Video;
import com.jin.webvideo.entity.VideoSearch;
import com.jin.webvideo.externalInterfaces.entity.Filmography;
import com.jin.webvideo.base.spi.InterfaceProvider;
import com.jin.webvideo.base.spi.anno.Register;
import com.jin.webvideo.mapper.VideoMapper;
import com.jin.webvideo.service.ApiService;
import com.jin.webvideo.util.entity.EntityUtil;
import com.jin.webvideo.util.base.StringUtil;
import com.jin.webvideo.util.base.URLUtil;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
@Register(name = "local")
public class LocalSearchInterface extends SearchInterface {

    @Autowired
    private VideoMapper videoMapper;
    @Autowired
    private ApiService apiService;

    public LocalSearchInterface(InterfaceProvider provider) {
        super(provider);
    }

    @Override
    protected List<Filmography> search(String key, String[] tags, int pageNo, int pageSize) throws Exception {
        key = URLUtil.decodeURL(key);
        key = StringUtil.join(key.toCharArray(), "%", true);
        int start = pageNo* pageSize;
        List<Video> videos = videoMapper.search(key, tags, start, -1, "local");
        List<Filmography> filmographyList = CollectionsUtil.convert(videos, (v) -> {
            Filmography f = EntityUtil.toFilmography(v);
            List<VideoInfo> list = videoMapper.findVideoInfoByDocid(v.getDocid(), "local");
            list.sort((o1,  o2) -> o1.getOrdin() - o2.getOrdin());
            f.setVideoInfos(EntityUtil.episode2VideoInfo(list));
            return f;
        });
        List<VideoSearch> videoSearche = videoMapper.selectSearchByName(key, start, -1);
        for (VideoSearch search : videoSearche) {
            String[] ids = EntityUtil.parse(search.getPlatform(), search.getUrl());
            Filmography f = apiService.getVideoInformation(search.getPlatform(), ids[0], ids[1]);
            filmographyList.add(0, f);
        }
        return filmographyList;
    }

    @Override
    protected int total(String key, String[] tags) throws Exception {
        key = URLUtil.decodeURL(key);
        key = StringUtil.join(key.toCharArray(), "%", true);
        return videoMapper.searchCount(key, tags, "local")
            + videoMapper.selectSearchCountByName(key);
    }
}
